package com.mud.dnd.ejb;

import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionManagement;

import com.mud.dnd.domain.common.DAOException;
import com.mud.dnd.domain.common.QueryParameter;
import com.mud.dnd.domain.dao.DnDDAO;
import com.mud.dnd.domain.model.Comment;
import com.mud.dnd.domain.model.User;
import com.mud.dnd.ejb.common.AuthenticationException;
import com.mud.dnd.ejb.services.AuthenticationService;

/**
 * Session Bean implementation class CommentManager
 */
@Stateless
@LocalBean
@TransactionManagement
public class CommentManager {

    @EJB
	private DnDDAO dao;
    
    
    @EJB
    private AuthenticationService userService;
    
    
    @TransactionAttribute
    public List<Comment> getComments(List<QueryParameter> params)
    {
    	List<Comment> comments =  dao.getComments(params);
    	
    	for(Comment comment : comments)
    	{
    		comment.setGameItemID(comment.getGameItem().getId());
    	}
    	
    	return comments;
    }
    
    
    @TransactionAttribute
    public int addComment(String message, String userName, int gameItemID, String sessionID) throws DAOException, AuthenticationException
    {
    	if(!userService.checkSessionForUser(userName, sessionID))
		{
			throw new AuthenticationException("Login required.");
		}
    	
    	User author = userService.getUserData(userName);
    	
    	Date creationDate = new Date();
    	
    	return dao.createComment(message, creationDate, author, gameItemID);
    }
    
    @TransactionAttribute
    public void deleteComment(int commentID,String userName,String sessionID ) throws DAOException, AuthenticationException
    {
    	if(!userService.checkSessionForUser(userName, sessionID))
		{
			throw new AuthenticationException("Login required.");
		}
    	if(!userService.checkIfUserIsOwner(userName, commentID))
		{
			throw new AuthenticationException("You can remove only your comment.");
			
		}
    	
    	dao.deleteComment(commentID);
    	
    	
    	
    }

}
